package com.liaoyifan.core.config;

import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
import com.alibaba.csp.sentinel.slots.system.SystemRule;
import com.alibaba.csp.sentinel.slots.system.SystemRuleManager;
import com.liaoyifan.core.aspect.WebAspect;
import com.liaoyifan.core.constant.Constants;
import com.liaoyifan.core.constant.Properties;
import com.liaoyifan.core.opera.SentinelExceptionHandler;
import jakarta.annotation.PostConstruct;
import java.util.List;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

@SuppressWarnings("unused")
@Configuration
@ConditionalOnProperty(name = Properties.SENTINEL_ENABLE, havingValue = Constants.TRUE)
public class SentinelConfiguration {

    @Bean
    @Primary
    public SentinelExceptionHandler sentinelExceptionHandler() {
        return new SentinelExceptionHandler();
    }

    @Bean
    @Primary
    public SentinelResourceAspect sentinelResourceAspect() {
        return new SentinelResourceAspect();
    }

    @PostConstruct
    public void initRules() {
        initSystemRules();
    }

    private void initSystemRules() {
        SystemRule rule = new SystemRule();
        rule.setHighestSystemLoad(Constants.CPU_COUNT * 0.9);
        rule.setHighestCpuUsage(0.9);
        rule.setAvgRt(WebAspect.SLOW);
        rule.setQps(500);
        rule.setMaxThread(500);
        SystemRuleManager.loadRules(List.of(rule));
    }
}
